package com.example.carborrow.dao;


import com.example.carborrow.model.Admin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
public class AdminDao {


    private final JdbcTemplate jdbcTemplate;

    @Autowired
    public AdminDao(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }


    private final  static String GET_ALL_ADS_SQL ="SELECT * FROM Admin";
    // 获取所有admin
    public List<Admin> getAllAdmin() {
        return jdbcTemplate.query(GET_ALL_ADS_SQL,new AdminRowMapper());
    }


    
    // 根据用户名查询amin
    private final static String GET_AD_BY_NAME_SQL = "SELECT * FROM Admin WHERE username = ?";
    public Admin getAdminByName(String name) {
        try {
            return jdbcTemplate.queryForObject(GET_AD_BY_NAME_SQL, new AdminRowMapper(), name);
        }catch (Exception e){
            return null;
        }

    }
    private final static String GET_AD_BY_IF_SQL = "SELECT * FROM Admin WHERE adminId = ?";
    public Admin getAdminById(int id) {
        try {
            return jdbcTemplate.queryForObject(GET_AD_BY_IF_SQL, new AdminRowMapper(), id);
        }catch (Exception e)
        {
            return null;
        }
    }



    private final static String ADD_AD_SQL = "INSERT INTO Admin (username,password) VALUES (?, ?)";
    //添加admin
    public int addAdmin(Admin admin) {
        return jdbcTemplate.update(ADD_AD_SQL, admin.getUserName(),admin.getPassword());
    }



    private final static String UPDATE_AD_BY_NAME_SQL ="UPDATE Admin SET password = ? WHERE username = ?";
    // 更新对应用户名的密码
    public int updateAdminByName(Admin admin) {
        return jdbcTemplate.update(UPDATE_AD_BY_NAME_SQL, admin.getPassword(), admin.getUserName());
    }


    private final static String UPDATE_AD_BY_ID_SQL ="UPDATE Admin SET password = ? WHERE adminId = ?";
    //按id更新密码
    public int updateAdminById(Admin admin) {
        return jdbcTemplate.update(UPDATE_AD_BY_ID_SQL, admin.getPassword(), admin.getAdminId());
    }

    private final static String DEL_AD_SQL="DELETE FROM Admin WHERE adminId = ?";
    //删除admin
    public int deleteAdmin(int adminId) {
        return jdbcTemplate.update(DEL_AD_SQL, adminId);
    }


    private static class AdminRowMapper implements RowMapper<Admin> {
        @Override
        public Admin mapRow(ResultSet rs, int rowNum) throws SQLException {
            Admin admin = new Admin();
            admin.setAdminId(rs.getInt("adminId"));
            admin.setUserName(rs.getString("username"));
            admin.setPassword(rs.getString("password"));

            return admin;
        }
    }

}
